import {createSlice} from "@reduxjs/toolkit";
import {getAllUserAPI, loginAPI} from "@/apis/user.jsx";
import {getToken, setToken} from "@/utils/token.jsx";

const userStore=createSlice({
    name:'userInfo',

    initialState:{
        token:getToken()||'',
        userList:[]
    },

    reducers:{

        // 修改数据的同步方法
        setUserInfo(state,action){
            state.token=action.payload;
            setToken(action.payload)
        },
    //     获取所有用户得同步方法
        getAllUser(state,action){
            state.userList=action.payload;
        }

        }
})
// 异步请求部分
const {setUserInfo,getAllUser}=userStore.actions;
// 获取登陆后返回得token
const fetchGetUserInfo=(data)=>{
    return async (dispatch)=>{
        const res=await loginAPI(data);
        dispatch(setUserInfo(res.data));
    }
}

// 获取所有用户信息
const fetchGetUserList=(current,pageSize)=>{
    return async (dispatch)=>{
        const res=await getAllUserAPI(current,pageSize);
        dispatch(getAllUser(res.data))
    }
}

const userInfoReducer=userStore.reducer;

export {setUserInfo,getAllUser,fetchGetUserInfo,fetchGetUserList}

export default userInfoReducer;